package com.zjitc.pigspring.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.zjitc.pigspring.bean.dto.Account;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

@Slf4j
public class TokenUtil {

    public static String getToken(Integer id,String role){
        return JWT.create().withAudience(id+"-"+role)    //将user id 保存到token里面，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))   //2小时后token过期
                .sign(Algorithm.HMAC256("mall"));     //以password作为token的密钥
    }

    public static Account getCurrentUser(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        log.info(token+"-------------");
        if (ObjectUtil.isNotEmpty(token)){
            String userID = JWT.decode(token).getAudience().get(0);
            Account account = new Account();
            account.setId(Integer.parseInt(userID.split("-")[0]));
            account.setRole(userID.split("-")[1]);
            return account;
        }
        return new Account();
    }

}
